package com.est.dase;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.widget.EditText;

import com.est.dase.database.CreateDataBaseDevice;
import com.est.dase.database.DataBase;
import com.est.dase.sms.SMS;
import com.est.dase.sms.SMSReceiverHandler;
import com.est.dase.sms.SmsReceiver;
import com.est.dase.widget.Status;
/**
 *
 * @author Fernando Geraldes, Jaime Santos, Jorge Silva
 *
 */
public class WAY implements WAYListener {

	SmsReceiver smsReceiver;
	EditText editNumber;
	SMS smsSender;
	Activity mainActivity;
	private DataBase db;
	String number;
	Location location;
	MyLocation myLocation = new MyLocation();

	public WAY(Activity mainActivity){

		SMSReceiverHandler.getInstance().registListener(this);

		this.mainActivity = mainActivity;
		smsReceiver = new SmsReceiver();
		smsSender = new SMS();
		CreateDataBaseDevice cdb = new CreateDataBaseDevice(mainActivity); 
		db = cdb.getDataBase();

	}

	public void received(final String from, final String message, Context context){

		location = myLocation.getLocation(context);

		number = from;         	

		if(message.equalsIgnoreCase(Params.way)){

			if (whiteList() && location != null){
				smsSender.sendSMS(number, Params.position+" "+location.getLatitude()+" "+location.getLongitude()+"", context);
				return;
			}else if (whiteList()){
				//Usado para resolver bug de nao ter posicao e tar na whitelist
				smsSender.sendSMS(number, context.getString(R.string.messageDisplay_send), context);
				return;
			}else if(blackList()){
				return;
			}else{
				Intent intent = new Intent(context, MessageDisplay.class);
				intent.putExtra("number", from);
				intent.putExtra("action", Params.way);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);  
			}

		}
		if(message.contains(Params.position)){
			Intent intent = new Intent(context, MapsClass.class);
			String[] message_split = message.split(" ");
			intent.putExtra("lat", message_split[1]);
			intent.putExtra("lon", message_split[2]);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);
		}
		if(message.equalsIgnoreCase(Params.wys)){

			if (whiteList()){
				smsSender.sendSMS(number, Params.wysStatus+" "+Status.getInstance(context).getCurrentStatus()+"", context);
				return;
			}

			if(blackList()){
				return;
			}

			Intent intent = new Intent(context, MessageDisplay.class);
			intent.putExtra("number", from);
			intent.putExtra("action", Params.wys);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);
		}

	}


	@SuppressWarnings("unused")
	private double[] displayMap(int cellID, int lac) throws Exception 
	{
		double[] latlong = new double[2];

		String urlString = "http://www.google.com/glm/mmap";            

		//---open a connection to Google Maps API---
		URL url = new URL(urlString); 
		URLConnection conn = url.openConnection();
		HttpURLConnection httpConn = (HttpURLConnection) conn;        
		httpConn.setRequestMethod("POST");
		httpConn.setDoOutput(true); 
		httpConn.setDoInput(true);
		httpConn.connect(); 

		//---write some custom data to Google Maps API---
		OutputStream outputStream = httpConn.getOutputStream();
		WriteData(outputStream, cellID, lac);       

		//---get the response---
		InputStream inputStream = httpConn.getInputStream();  
		DataInputStream dataInputStream = new DataInputStream(inputStream);

		//---interpret the response obtained---
		dataInputStream.readShort();
		dataInputStream.readByte();
		int code = dataInputStream.readInt();
		if (code == 0) {
			double lat = (double) dataInputStream.readInt() / 1000000D;
			double lng = (double) dataInputStream.readInt() / 1000000D;
			latlong[0] = lat;
			latlong[1] = lng;
			return latlong;
		}
		else
		{        	
			return latlong;
		}
	}



	private void WriteData(OutputStream outputStream, int cellID, int lac)  throws IOException {
		DataOutputStream os = new DataOutputStream(outputStream);
		os.writeShort(21);
		os.writeLong(0);
		os.writeUTF("pt");
		os.writeUTF("LG_P500");
		os.writeUTF("1.3.1");
		os.writeUTF("Web");
		os.writeByte(27);

		os.writeInt(0); os.writeInt(0); os.writeInt(3);
		os.writeUTF("");
		os.writeInt(cellID); // CELL-ID
		os.writeInt(lac); // LAC
		os.writeInt(0); os.writeInt(0);
		os.writeInt(0); os.writeInt(0);
		os.flush();

	} 

	@SuppressWarnings("rawtypes")
	public boolean whiteList(){

		String sqlStatement = "SELECT * FROM WHITE_LIST";
		final HashMap[] hash = sqlStatement(sqlStatement);

		boolean status = false;

		String num = number.replaceAll("\\+351", "");

		if(hash.length > 0){
			for(int i=0; i<hash.length; i++){
				String n = hash[i].get("NUMBER").toString().replaceAll("-", "");
				//System.out.println("NUMBER: " + n + "\n" + num); 
				if(n.equals(num)){
					status = true;
				}
			}
		}
		return status;
	}

	@SuppressWarnings("rawtypes")
	public boolean blackList(){
		String sqlStatement = "SELECT * FROM BLACK_LIST";
		final HashMap[] hash = sqlStatement(sqlStatement);

		boolean status = false;

		String num = number.replaceAll("\\+351", "");

		if(hash.length > 0){
			for(int i=0; i<hash.length; i++){
				String n = hash[i].get("NUMBER").toString().replaceAll("-", "");
				//System.out.println("NUMBER: " + n + "\n" + num); 
				if(n.equals(num)){
					status = true;
				}
			}
		}
		return status;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public HashMap[] sqlStatement(String sqlStatement) {
		//db.close();
		SQLiteDatabase dbEvent = db.getReadableDatabase();
		Cursor cursor = dbEvent.rawQuery(sqlStatement, null);
		HashMap[] hash = new HashMap[cursor.getCount()];

		mainActivity.startManagingCursor(cursor);
		cursor.moveToPrevious();

		for(int j=0;j<cursor.getCount();j++){
			hash[j]=new HashMap<String, String>();
			cursor.moveToNext();			
			for(int i=0;i<cursor.getColumnCount();i++){
				hash[j].put(cursor.getColumnName(i), cursor.getString(i));
			}
		}
		db.close();
		return hash;
	}
}